package com.ygqh.baby.controller.mobile;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgAgentInviteRecord;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心
 *
 * @author guohao
 */
@Controller
@RequestMapping("/app/userCentre")
public class YgUserCentreController extends BaseController {

	@Autowired
	private YgUserService userService;
	@Autowired
	private YgOrderService orderService;
	@Autowired
	private YgProductCommentService productCommentService;
	@Autowired
	private FileService fileService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;
	@Autowired
	private YgUserMemberService ygUserMemberService;
	@Autowired
	private WxSmallAuthorityService wxSmallAuthorityService;
	@Autowired
	private YgCouponDetailService ygCouponDetailService;

	@Value("${image.domain}")
	private String domain;
	@Value("${image.upload.temp.url}")
	private String tempDir;
	@Value("${promotion.link}")
	protected String promotionLink;

	/**
	 * 获取用户信息
	 *
	 * @return
	 */
	@RequestMapping(value = "findUserInfo")
	@ResponseBody
	public ResponseEntity findUserInfo() {
		YgUser user = SessionUtil.getCurrentUser();
		YgUserModel userInfo = userService.findUserInfo(user.getId());
		String birthday = DateConvertUtils.getBabyBirthday(userInfo.getBabyBirthday());
		userInfo.setbBirthday(birthday);
		userInfo.setSourceCode(user.getSourceCode());
		String fromCode = user.getFromCode();
		YgAgentInviteRecord record = ygAgentInviteRecordService.findRecordForYijiandian(user.getId());
		if (record != null) {
			String code = ShareCodeUtil.toSerialCode(record.getUserId());
			if (!code.equals(fromCode)) {
				fromCode = code;
			}
		} else {
			fromCode = "";
		}
		userInfo.setFromCode(fromCode);
		return ResponseEntity.success(userInfo);
	}

	/**
	 * 更新用户信息
	 *
	 * @param userLogo
	 * @param nickName
	 * @param babyGender
	 * @param babyBirthday
	 * @return
	 */
	@RequestMapping(value = "updateUserInfo")
	@ResponseBody
	public ResponseEntity updateUserInfo(String userLogo, String nickName, Integer babyGender, Date babyBirthday) {
		YgUser user = SessionUtil.getCurrentUser();
		if (StringUtil.isNotBlank(nickName)) {
			if (nickName.length() >= 50) {
				return ResponseEntity.error("昵称超长");
			}
		}
		int row = userService.updateUserInfo(user.getId(), userLogo, nickName, babyGender, babyBirthday);
		return ResponseEntity.success(row);
	}

	/**
	 * 获取不同状态下订单数量
	 *
	 * @return
	 */
	@RequestMapping(value = "findCountByOrderStatus")
	@ResponseBody
	public ResponseEntity findCountByOrderStatus() {
		YgUser user = SessionUtil.getCurrentUser();
		List<Map<String, Object>> maps = orderService.findCountByOrderStatus(user.getId(), PLATFORM_NO);
		int unCommentComplete = orderService.countUnCommentComplete(user.getId(), PLATFORM_NO);
		for (Map<String, Object> map : maps) {
			if (map.get("orderStatus").equals("TradeSuccess")) {
				map.put("amount", unCommentComplete);
			}
		}
		return ResponseEntity.success(maps);
	}


	/**
	 * 个人中心获取订单列表
	 *
	 * @param queryInfo
	 * @param orderStatus
	 * @return
	 */
	@RequestMapping(value = "findMyOrderList")
	@ResponseBody
	public ResponseEntity findMyOrderList(QueryInfo queryInfo, OrderStatus orderStatus) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgOrderModel> orderList = orderService.findOrderList(queryInfo, user.getId(), orderStatus, PLATFORM_NO);
		return ResponseEntity.success(orderList);
	}

	/**
	 * 个人中心 由订单列表进入某一订单详情页
	 *
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "findOrderInfo")
	@ResponseBody
	public ResponseEntity findOrderInfo(Long orderId) {
		YgUser user = SessionUtil.getCurrentUser();
		YgOrderInfoModel model = orderService.findOrderInfo(orderId, user.getId());
		return ResponseEntity.success(model);
	}

	@RequestMapping(value = "findOrderInfoKF")
	@ResponseBody
	public ResponseEntity findOrderInfoKF(Long orderId) {
		YgOrderInfoModel model = orderService.findOrderInfo(orderId, null);
		return ResponseEntity.success(model);
	}

	/**
	 * 获取订单物流信息
	 *
	 * @param expCode
	 * @param expNo
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "getLogisticsInfo")
	@ResponseBody
	public ResponseEntity getLogisticsInfo(String expCode, String expNo) {

		Message msg = orderService.getLogisticsInfo(expCode, expNo);

		return ResponseEntity.converter(msg);
	}

	/**
	 * 获取该订单所有商品评论情况
	 *
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "findWaitingComment")
	@ResponseBody
	public ResponseEntity findWaitingComment(Long orderId) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgOrder4CommentModel> models = orderService.findWaitingComment(orderId, user.getId());
		return ResponseEntity.success(models);
	}

	/**
	 * 提交商品评论
	 *
	 * @param orderId
	 * @param productId
	 * @param skuId
	 * @param content
	 * @param imagesUrls
	 * @param commentTags
	 * @return
	 */
	@RequestMapping(value = "commentOrderItem")
	@ResponseBody
	public ResponseEntity commentOrderItem(Long orderId, Long productId, Long skuId, String content, String imagesUrls, CommentTag[] commentTags, Long couponBatchId) {
		YgUser user = SessionUtil.getCurrentUser();
		if (content.length() >= 300) {
			return ResponseEntity.error("评论内容超长", content);
		}
		Long couponDetailId = 0L;
		// 评论送券
		Boolean isFirstComment = true;
		Map<String, Long> map = orderService.orderIsComment(orderId);
		Long commentCount = map.get("commentCount");
		if (commentCount.intValue() > 0) {
			isFirstComment = false;
		}
		YgOrder order = orderService.findByOrderId(orderId);
		if (order.getUserId().intValue() == user.getId().intValue() &&
				isFirstComment) {
			try {
				Message msg = ygCouponDetailService.receiveIncreateCoupon(couponBatchId, user);
				couponDetailId = (Long) msg.getExtra();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		productCommentService.commentOrderItem(orderId, user, productId, skuId, content, imagesUrls, commentTags, couponDetailId);
		return ResponseEntity.success("评价成功");
	}


	@RequestMapping(value = "isNewCustom")
	@ResponseBody
	public ResponseEntity isNewCustom() {
		YgUser user = SessionUtil.getCurrentUser();
		Boolean newCustom = userService.isNewCustom(user.getId());
		return ResponseEntity.success(newCustom);
	}

	/**
	 * 个人中心获取推荐用户
	 *
	 * @param queryInfo
	 * @return
	 */
	@RequestMapping(value = "findRecommendUser")
	@ResponseBody
	public ResponseEntity findRecommendUser(QueryInfo queryInfo) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserRecommendModel> userRecommendList;
		if (UserType.Group.equals(user.getUserType())) {
			userRecommendList = userService.findUserRecommend(queryInfo, null, user.getGroupTag());
		} else {
			userRecommendList = userService.findUserRecommend(queryInfo, user.getSourceCode(), null);
		}
		return ResponseEntity.success(userRecommendList);
	}

	@SuppressWarnings("deprecation")
	@RequestMapping("getTGZYCodeUrl")
	@ResponseBody
	public ResponseEntity getTGZYCodeUrl(String qrCodeName, HttpServletRequest request) throws UnsupportedEncodingException {
		YgUser user = SessionUtil.getCurrentUser();
		String url = promotionLink + "?sourceCode=" + user.getSourceCode();
		String path = request.getRealPath("/");
		String realPath = path + "/TGZYCodeImage";
		String fileName = "TGZY" + user.getSourceCode() + ".jpg";
		String qtcodeUrl = "";
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			realPath = QRCodeUtil.encode(url, realPath, fileName);
			if (!StringUtil.isBlank(realPath)) {
				String ext = fileName.split("\\.")[1];
				String yunTupian = HttpUtil.saveImageToDisk(domain + "/default/" + qrCodeName + ".jpg", realPath);
				ImageUtils.pressImageMark(realPath, yunTupian, realPath, 0, 0, 1.0f);
				File file = new File(realPath);
				qtcodeUrl = fileService.uploadImage(file, new FileType[]{FileType.QrCode}, ext, true, request);
			}
		} catch (Exception e) {
			logger.debug("生成推广二维码失败.sourceCode = " + user.getSourceCode());
			e.printStackTrace();
		}
		// 生成推广短连接
		map.put("codeUrl", qtcodeUrl);
		return ResponseEntity.success(map);
	}

	private Boolean isReceived(Long userId) {
		String result = redisDao.get("715ZHANHUI-" + userId);
		if (StringUtil.isNotBlank(result)) {
			return true;
		}
		return false;
	}

	@RequestMapping(value = "getMapVipPrice")
	@ResponseBody
	public ResponseEntity getMapVipPrice() {
		Map<String, BigDecimal> map = ygUserMemberService.getMapVipPrice();
		return ResponseEntity.success(map);
	}

	/**
	 * 粉丝列表
	 *
	 * @param queryInfo 分页
	 * @return
	 * @date 2019/04/02 10:58
	 * @version 2.0
	 */
	@RequestMapping(value = "findRecommendUser", params = {"version=2.0"})
	@ResponseBody
	public ResponseEntity findRecommendUserV2(QueryInfo queryInfo) {
		YgUser user = SessionUtil.getCurrentUser();
		Map<String, Object> dataMap = ygAgentInviteRecordService.findRecommendUserCount(user.getId(), PLATFORM_NO);
		List<YgUserRecommendModel> userRecommendList = ygAgentInviteRecordService.
				findRecommendUser(queryInfo, user, PLATFORM_NO);
		dataMap.put("userRecommendList", userRecommendList);
		return ResponseEntity.success(dataMap);
	}

	/**
	 * 邀请用户分享图
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("shareCodeImage")
	@ResponseBody
	public ResponseEntity shareCodeImage() throws Exception {
		YgUser currentUser = SessionUtil.getCurrentUser();
		String key = String.format(RedisConstant.YIJIADIAN_USER_SHARE_PREFIX_KEY, currentUser.getId());
		String imageUrl = redisDao.get(key);
		if (StringUtils.isNotBlank(imageUrl)) {
			imageUrl = imageUrl.replace("http://img.yiigoo.com", "https://yiigoo-pro.oss-cn-beijing.aliyuncs.com");
			return ResponseEntity.success(imageUrl);
		}
		String filePathAfterPress = tempDir + key + ".jpg";
		// 底图地址
		String srcImageFile = getShareDitu();
		// 小程序码
		String smallQrcode = getSmallQrcode(key, currentUser.getId());
		if (StringUtils.isBlank(smallQrcode)) {
			return ResponseEntity.error("生成分享图异常，请稍后重试", null);
		}
		String press = tempDir + currentUser.getUserName() + ".jpg";
		try {
			ImageUtils.makeCircularImgByUrl(smallQrcode, press);
		} catch (Exception e) {
			redisDao.del(key + "_wxacode"); // 小程序码异常，删除无效缓存
			logger.error("【邀请用户分享图】下载小程序码时异常，key=" + key + "，smallQrcode=" + smallQrcode, e);
			return ResponseEntity.error("生成分享图异常，请稍后重试", null);
		}
		ImageUtils.pressImageMark2(press, srcImageFile, filePathAfterPress,
				290, 900, 1.0f, 165, 165);
		File file = new File(filePathAfterPress);
		if (!file.exists()) {
			logger.error("【邀请用户分享图】生成的文件 '" + key + ".jpg'不存在");
			return ResponseEntity.error("生成分享图异常，请稍后重试", null);
		}
		String codeUrl = fileService.uploadImage(file, FileType.Temp, true);
		redisDao.set(key, codeUrl, 24 * 60 * 60 * 1000);
		codeUrl = codeUrl.replace("http://img.yiigoo.com", "https://yiigoo-pro.oss-cn-beijing.aliyuncs.com");
		return ResponseEntity.success(codeUrl);
	}

	private String getSmallQrcode(String prefixKey, Long userId) {
		String key = prefixKey + "_wxacode";
		String smallQrcode = redisDao.get(key);
		if (StringUtils.isNotBlank(smallQrcode)) {
			return smallQrcode;
		}
		logger.info("[getSmallQrcode] 缓存中未获取到小程序码，调取微信接口生成，redisKey={}", key);
		String url = "pages/agent/newuser/newuser?sourceCode=" + ShareCodeUtil.toSerialCode(userId);
		smallQrcode = wxSmallAuthorityService.getSamllQrcode(url, 1, PLATFORM_NO);
		if (StringUtils.isBlank(smallQrcode)) {
			return null;
		}
		redisDao.set(key, smallQrcode, 0);
		return smallQrcode;
	}

	private String getShareDitu() {
		String fileName = "yijiadian_user_share_ditu.jpg";
		// 底图阿里云路径
		String sourceUrl = domain + "default/" + fileName;
		// 本地路径
		String localPath = tempDir + "/" + fileName;
		File localFile = ImageUtils.getFile(localPath);
		if (!localFile.exists()) {
			ImageUtils.saveImageToDisk(sourceUrl, tempDir, fileName);
		}
		return localPath;
	}

	/**
	 * 邀请用户二维码（壹家店）
	 *
	 * @return
	 */
	@RequestMapping("inviteCode")
	@ResponseBody
	public ResponseEntity getInviteCode() {
		YgUser currentUser = SessionUtil.getCurrentUser();
		String key = String.format(RedisConstant.YIJIADIAN_USER_SHARE_PREFIX_KEY, currentUser.getId());
		// 小程序码
		String smallQrcode = getSmallQrcode(key, currentUser.getId());
		if (StringUtils.isBlank(smallQrcode)) {
			return ResponseEntity.error("生成分享图异常，请稍后重试", null);
		}
		smallQrcode = smallQrcode.replace("http://img.yiigoo.com", "https://yiigoo-pro.oss-cn-beijing.aliyuncs.com");
		return ResponseEntity.success(smallQrcode);
	}
}
